<?php

namespace app\server\tcp\controller;

use app\server\inter\WorkerDriver;
use app\server\model\ControlCommand;
use app\server\model\ControlCommandSimple;
use app\server\model\ControlFilter;


/**
 * 远程控制器 子进程
 *
 * Class ControlHttp
 * @package app\server\tcp\controller
 */
class ControlHttp implements WorkerDriver
{
    /**
     * 主进程链接容器
     *
     * @var array
     */
    public $tcpConnectObj = [];


    /**
     * 连接回调
     *
     * @param $connect
     */
    public function onConnect($connect)
    {
        echo "in http......\n\r";
        $filter = new ControlFilter('http');
        $clientIp = $connect->getRemoteAddress();
        echo "ip------" . $clientIp . "------in......" . PHP_EOL;
        if (!$filter->checkClient($clientIp)) {
            echo "tcp:unauthorized" . PHP_EOL;
            $connect->close('未授权的请求');
        }
    }

    /**
     * 消息回调
     *
     * @param $httpConnect
     * @param $data
     * @return mixed
     */
    public function onMessage($httpConnect, $data)
    {
        if (empty($_GET['code'])) {
            return $httpConnect->send('fail');
        }

        if ( ! empty($_GET['to']) && !isset($this->tcpConnectObj[$_GET['to']])) {
            return $httpConnect->send('offline');
        }
        $to = $_GET['to'];

        echo $_GET['code'] . '----code' . PHP_EOL;

        $control = new ControlCommand();
        $control->setStrategy(new ControlCommandSimple($_GET['code']));

        // 获得内置命令
        $commands = $control->run();
        if (empty($commands)) {
            return $httpConnect->send('code error');
        }

        if (is_array($commands)) {
            $this->tcpConnectObj[$to]->send(hex2bin($commands[0]));
            sleep($commands['time']);
            $this->tcpConnectObj[$to]->send(hex2bin($commands[1]));
        } else {
            $this->tcpConnectObj[$to]->send(hex2bin($commands));
        }

        return $httpConnect->send('ok');
    }

    /**
     * 子进程开始
     *
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        echo 'start child' . PHP_EOL;
    }


    /**
     * @param $connection
     */
    public function onBufferFull($connection)
    {
        // TODO: Implement onBufferFull() method.
    }

    /**
     * @param $connection
     */
    public function onBufferDrain($connection)
    {
        // TODO: Implement onBufferDrain() method.
    }

    /**
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "abort......" . PHP_EOL;
        print_r($msg);
        echo "abort......" . PHP_EOL;
    }

    /**
     * @param $connection
     */
    public function onClose($connection)
    {
        echo "out......" . PHP_EOL;
    }

}